using Microsoft.AspNetCore.Identity;
using SageKing.OpenIddict.UI.Infrastructure.Data;


namespace SageKing.Blazor.OpenIdService.Services
{
    internal sealed class IdentityUserAccessor(
        UserManager<AppUser> userManager,
        IdentityRedirectManager redirectManager,
        AuthenticationStateProvider AuthProvider)
    {
        public CustomAuthStateProvider context = ((CustomAuthStateProvider)AuthProvider);

        public async Task<AppUser> GetRequiredUserAsync()
        {
            var state = await context.GetAuthenticationStateAsync();

            var user = await userManager.GetUserAsync(state.User);

            if (user is null)
            {
                redirectManager.RedirectToWithStatus("Account/InvalidUser", $"Error: Unable to load user with ID '{userManager.GetUserId(context.User)}'.", null);
              
            }

            return user;
        }
    }
}
